//
//  FSLoginViewController.m
//  贸促会
//
//  Created by 刘沿 on 16/3/31.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSLoginViewController.h"
#import "XmlParseHelper.h"
#import "AuthHelper.h"
@interface FSLoginViewController ()<UITextFieldDelegate,SangforSDKDelegate>

@property (nonatomic, strong) AuthHelper *helper;

@end

@implementation FSLoginViewController
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
NSString *userName = @"ccpitzjapp";             //用户名认证的用户名
NSString *password = @"ccpitzjappapp";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] != 0) {
        
        self.usernameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] != 0) {
        
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
        self.autoLogin.selected = YES;
    }


}
#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
           // NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            //NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            //NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
           // NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
               // NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
            //            证书认证
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
               // NSLog(@"PATH = %@",authPaths);
                //P12证书路径
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                //证书的密码
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
           // NSLog(@"Start Cert Auth!!!");
            break;
            
            /** 用户名密码认证 */
        case SSL_AUTH_TYPE_PASSWORD:
           // NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            
            break;
            /** 无认证 */
        case SSL_AUTH_TYPE_NONE:
           // NSLog(@"Auth success!!!");
             [self setin];

            return;
        default:
            //NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
// 注销第一响应者
    [textField resignFirstResponder];
    
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.usernameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];

}


//记住密码按钮点击
- (IBAction)recoardAction:(id)sender {
    self.recordPassWord.selected = !self.recordPassWord.selected;
    
//    
    if (!self.recordPassWord.selected) {
        self.autoLogin.selected = self.recordPassWord.selected;
    }
    
}



//自动登录按钮----MaoCuHui才有
- (IBAction)autoLogin:(UIButton *)sender {
    
    self.autoLogin.selected = !self.autoLogin.selected;

}
#pragma mark-------登录按钮点击

- (IBAction)login:(UIButton *)sender {
//if ([_type isEqualToString:@"1"]) {
//    [self setin ];
//}
//else{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
 if (self.usernameTextField.text.length == 0) {
        
        [self.view makeToast:@"请输入账号"];
        return;
    }
    
    if (self.passwordTextField.text.length == 0) {
        
        [self.view makeToast:@"请输入密码"];
        return;
    }else{
 MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登录,请稍等";
                [NSThread sleepForTimeInterval:1.0];

// self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
          if([_helper queryVpnStatus] ==VPN_STATUS_OK){
  [self setin];
 
 }else{
  self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//     [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];

 }
}
//}


}

- (void)setin{
  [self.usernameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    if (self.usernameTextField.text.length == 0) {
        
        [self.view makeToast:@"请输入账号"];
        return;
    }
    
    if (self.passwordTextField.text.length == 0) {
        
        [self.view makeToast:@"请输入密码"];
        return;
    }
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
         NSString *strUrl = [self.usernameTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
         strUrl = [strUrl lowercaseString];

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:strUrl forKey:@"userId"];
    [params setObject:self.passwordTextField.text forKey:@"pwdId"];
    
    [HttpTools postWithURL:KexchURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text}] method:@"validationUser" success:^(id JSON) {
         //NSLog(@"%@",JSON);
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        XmlParseHelper *parse = [[XmlParseHelper alloc] initWithData:JSON];
        
        NSArray *resultArray = [parse selectNodes:@"errmsg"];
        
        NSString *resultTag = nil;
        if (resultArray.count) {
            NSDictionary *dict = [resultArray lastObject];
            
            resultTag = dict[@"text"];
        }
        FSMainViewController_Second *mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MainVC_2"];
        UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:mainVC];
        
        switch ([resultTag integerValue]) {
            case 1:
                [self.view makeToast:@"您的用户名不存在，请确认后再输"];
                break;
            case 2:
                self.view.window.rootViewController = navVC;
                // 存储账号密码
                if (self.recordPassWord.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
                    
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
                }
                
                if (!self.autoLogin.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
                }
                break;
            case 3:
                [self.view makeToast:@"密码错误"];
                
                break;
                
            default:
                break;
        }
        
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
    }];

}

@end









